﻿using System.Collections;
using System.Linq;
using Pap.Core.Utilities;
using Pap.Data;
using Pap.Services.WorkflowEngine;
using Pap.Web.Utils;

namespace Pap.Web.Modules.Loan.ViewModels
{
    /// <summary>
    /// 
    /// </summary>
    public class FreezLoansViewModel : IViewModel
    {
        #region [ fields ]
        /// <summary>
        /// 
        /// </summary>
        private ILoanRepository _loanRepository;
        /// <summary>
        /// 
        /// </summary>
        private WorkflowService _workflowService;
        #endregion

        #region [ Constructors ]
        /// <summary>
        /// Initializes a new instance of the <see cref="FreezLoansViewModel"/> class.
        /// </summary>
        /// <param name="loanRepository">The loan repository.</param>
        /// <param name="workflowService">The workflow service.</param>
        public FreezLoansViewModel(ILoanRepository loanRepository, WorkflowService workflowService)
        {
            _loanRepository = loanRepository;
            _workflowService = workflowService;
        }
        #endregion

        #region [ Methods ]
        /// <summary>
        /// Gets the frozen loans.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetFrozenLoans()
        {
            var loanIds = _workflowService.GetInStep(Steps.PostponeListWithoutResearchandStudy).Union(
                    _workflowService.GetInStep(Steps.PostponeListWithResearchandStudy));

            return from loan in _loanRepository.FindCustomerLoans(loan => loanIds.Contains(loan.LoanID))
                   select new
                              {
                                  loan.LoanID,
                                  loan.LoanNumber,
                                  loan.LoanName,
                                  loan.CustomerObj.CustomerName,
                                  loan.LoanAmount,
                                  loan.LoanPaymentMethodObj.LoanPaymentMethodName,
                                  loan.LoanPaymentPeriod
                              };
        }
        #endregion

        internal void UnfreezLoan(System.Guid loanID)
        {
            _workflowService.Move(Services.WorkflowEngine.ActionTypes.Unfreeze, _workflowService.GetProcessInstanceIDByEntity(loanID), RegistryInfo.UserID, string.Empty, null);
        }
    }
}